<?php
declare (strict_types = 1);
namespace app\api\controller;

use think\facade\Cache;
use think\facade\Db;

/**
 * 跨站售票
 */
class NetSellTicket
{
    //公共查询
    /**
     * 班次列表查询
     * @Author   xiaoxiao972521
     * @DateTime 2019-10-27T15:53:26+0800
     * @return   [type]                   [description]
     */
    public function queryBusList(){
        //判断传入方法是否为POST
        if(request()->method() == "POST"){
            //获取传入数据
            $data = request()->POST();
            //联合查询相关信息
            $result = Db::table('U_xlzdb')
            ->join('U_xlb', 'U_xlzdb.xlbh = U_xlb.xlbh')
            ->join('U_jhb', 'U_xlzdb.xlbh = U_jhb.xlbh')
            ->join('U_clb', 'U_jhb.ysbbkh = U_clb.bbkh')
            ->where([
                ['U_xlzdb.mdzm', '=', $data['arrivalDepot']],
                ['U_xlzdb.mdzh', '=', $data['arrivalArea']],
                ['U_xlb.xlzt', '=', '正常'],
                ['U_jhb.ysbj', '=', '1'],
                ['U_jhb.ysfcsj', 'like', $data['departDate'] . '%']
                //['U_jhb.bczt', '=', '已报']
            ])
            ->field([
                'U_jhb.ysfcsj', 
                'U_jhb.bcbh', 
                'U_jhb.bclx', 
                'U_xlzdb.mdzm',
                'U_jhb.xlmc', 
                'U_xlzdb.ptpj', 
                'U_xlzdb.zdpj', 
                'U_xlzdb.hhpj', 
                'U_xlzdb.tbpj', 
                'U_xlb.ssgs', 
                'U_xlzdb.xlbh',
                'U_xlzdb.lc',
                'U_clb.zwgs',
                'U_xlzdb.mdzh',
                'U_jhb.ysbbkh'])
            ->select();
            //判断车辆是否存在
            if(!count($result)){
                return json([
                    'code' => '1000007',
                    'msg' => '查询失败，没有找到该车辆',
                ]);
            }
            //递增变量,定义数组
            $i = 0;
            $json_data = [];
            //传递syzw
            foreach($result as $key){
                //判断当前车辆键值是否存在
                if(Cache::store('redis')->exists($key['ysbbkh'] . '_' . $key['ysfcsj'])){
                    //调取redis内数据
                    $key['syzw'] = count(Cache::store('redis')->get($key['ysbbkh'] . '_' . $key['ysfcsj']));
                    $json_data[$i] = $key;
                }else{
                    //生产座位数据
                    for ($a = 1; $a <= $key['zwgs']; $a++) { 
                        $used[$a] = $a;
                    }
                    //将当前车辆座位信息存放至redis
                    Cache::store('redis')->set($key['ysbbkh'] . '_' . $key['ysfcsj'], $used);
                    $key['syzw'] = $key['zwgs'];
                    $json_data[$i] = $key;
                }
                $i = $i + 1;
            }
            //返回信息
            return json([
                'code' => '01',
                'msg' => '成功',
                'data' => $json_data
            ]);
        }else{
            //404，针对Get数据或其他数据
            throw new \think\exception\HttpException(404, '页面不存在~');
        }
    }

    /**
     * 班次详情查询
     * @Author   xiaoxiao972521
     * @DateTime 2019-10-28T15:26:42+0800
     * @return   [type]                   [description]
     */
    public function queryBusDetail(){
        //判断传入方法是否为POST
        if(request()->method() == "POST"){
            //获取传入的数据
            $data = request()->POST();
            //联合查询数据
            $result = Db::table('U_xlzdb')
            ->join('U_xlb', 'U_xlzdb.xlbh = U_xlb.xlbh')
            ->join('U_jhb', 'U_xlzdb.xlbh = U_jhb.xlbh')
            ->join('U_clb', 'U_jhb.ysbbkh = U_clb.bbkh')
            ->where([
                ['mdzm', '=', $data['arrivalDepot']],
                ['U_xlb.ssgs', '=', $data['busGroupCode']],
                ['U_jhb.bcbh', '=', $data['busCode']],
                ['U_xlb.xlzt', '=', '正常'],
                ['U_jhb.ysbj', '=', '1'],
                ['U_jhb.ysfcsj', '=', $data['departTime']]
                //['U_jhb.bczt', '=', '已报']
            ])
            ->field([
                'U_jhb.ysfcsj',
                'U_jhb.ysbbkh',
                'U_jhb.bcbh',
                'U_xlzdb.lc',
                'U_xlzdb.mdzm',
                'U_xlzdb.ptpj',
                'U_xlzdb.zdpj',
                'U_xlzdb.hhpj',
                'U_xlzdb.tbpj',
                'U_xlb.ssgs',
                'U_clb.zwgs', 
                'U_xlzdb.xlbh', 
                'U_xlzdb.mdzh'])
            ->select();
            //判断车辆是否存在
            if(!count($result)){
                return json([
                    'code' => '1000007',
                    'msg' => '查询失败，没有找到该车辆',
                ]);
            }
            //递增变量,定义数组
            $i = 0;
            $json_data = [];
            //传递syzw
            foreach($result as $key){
                //判断当前车辆键值是否存在
                if(Cache::store('redis')->exists($key['ysbbkh'] . '_' . $key['ysfcsj'])){
                    //调取redis内数据
                    $key['syzw'] = count(Cache::store('redis')->get($key['ysbbkh'] . '_' . $key['ysfcsj']));
                    $json_data[$i] = $key;
                }else{
                    //循循生成座位信息
                    for ($a = 1; $a <= $key['zwgs']; $a++) { 
                        $used[$a] = $a;
                    }
                    //将当前车辆信息存入Redis
                    Cache::store('redis')->set($key['ysbbkh'] . '_' . $key['ysfcsj'], $used);
                    $key['syzw'] = $key['zwgs'];
                    $json_data[$i] = $key;
                }
                $i = $i + 1;
            }
            //返回数据
            return json([
                'code' => '01',
                'msg' => '成功',
                'data' => $json_data
            ]);
        }else{
            //404
            throw new \think\exception\HttpException(404, '页面不存在~');
        }
    }

    /**
     * 当前票号查询
     * @Author   xiaoxiao972521
     * @DateTime 2019-11-11T15:59:55+0800
     * @return   [type]                   [description]
     */
    public function queryCurrentNumber(){
        if(request()->method() == "POST"){
            $data = request()->POST();
            //接收工号(怀疑是用户信息)
            $gh = $data['jobNumber'];
            //查询Cpb信息
            $result = Db::table('U_cpb')
            ->where([
                ['sfzh', '=', $gh],
                ['qpbj', '<>', '已取']
            ])
            ->field([
                'cpbh'/* as 'invoiceCode',
                'cpbh' as 'invoiceNum'*/
            ])
            ->select();
            //判断票是否存在
            if(!count($result)){
                return json([
                    'code' => '10000015',
                    'msg' => '查询失败，没有符合特征的车票'
                ]);
            }
            $return_data = [];
            if(count($result)){
                //构建返回数据
                foreach($result as $key){
                    $key['SurplusNum'] = count($result);
                    $return_data = $key;
                }
                //返回数据
                return json([
                    'code' => '01',
                    'msg' => '成功',
                    'data' => $return_data
                ]);
            }
        }else{
            //404
            throw new \think\exception\HttpException(404, '页面不存在~');
        }
    }

    /**
     * 行前取票查询
     * @Author   xiaoxiao972521
     * @DateTime 2019-12-18T15:52:05+0800
     * @return   [type]                   [description]
     */
    public function queryFetchTicket(){
        if (request()->method() == "POST") {
            $data = request()->POST();
            //使用取票号和取票密码来获取信息
            $result = Db::table('U_ddb')
                    ->where([
                        ['U_ddb.qph', '=', $data['takeNum']],
                        ['U_ddb.qpmm', '=', md5($data['takeNum'])],
                        ['U_ddb.ddzt', '=', '1'],
                    ])
                    ->field([
                        'fcsj',
                        'bcbh',
                        'qszh',
                        'mdzh',
                        'jpk',
                        'ddh',
                    ])
                    ->select();
            $i = 0;
            foreach ($result as $key) {
                //查询符合条件的cp信息
                $result_cus = Db::table('U_cpb')
                        ->where('ssdd', '=', $key['ddh'])
                        ->field([
                            'elTicket',
                            'cplx',
                            'pj',
                            'tbpj',
                            'zwh',
                            'sfzh',
                            'lkxm',
                        ])
                        ->select();
                //重新构建数据
                foreach($result_cus as $cus){
                    $custom[$i] = $cus;
                }
                $i = $i + 1;
            }
            //判断数据不为空
            if(count($result) && count($custom)){
                //返回信息
                return json([
                    'code' => '01',
                    'msg' => '成功',
                    'data' => [
                        'result' => $result,
                        'custom' => $custom,
                    ],
                ]);
            }else{
                return json([
                    'code' => '10000014',
                    'msg' => '请求无效',
                ]);
            }
        }else{
            //不再是404，未测试哪种方式更优秀
            return json([
                'code' => '10000013',
                'msg' => '请求方法错误,请稍后重试',
            ]);
        }
    }

    /**
     * 行前取票
     * @Author   xiaoxiao972521
     * @DateTime 2020-01-06T16:15:05+0800
     * @return   [type]                   [description]
     */
    public function entityTicketFetch(){
        if (request()->method() == "POST") {
            $data = request()->POST();
            try {
                //获取当前时间
                $time = date('Y-m-d H:i:s', time());
                //事务开始
                Db::startTrans();
                //获取符合条件的车票信息，并更新
                $result = DB::table('U_cpb')
                ->where([
                    ['cpbh', '=', $data['invoiceCode']],
                    ['qpbj', '<>', '已取'],
                    ['sfzh', '=', $data['jobNumber']]
                ])
                ->update([
                    'qpbj' => '已取'
                ]);
                //事务提交
                Db::commit();
                //返回数据
                return json([
                    'code' => '01',
                    'message' => '成功',
                    'data' => [
                        'time' => $time
                    ]
                ]);
            } catch (Exception $e) {
                //事务回滚
                Db::rollBack();
                return json([
                    'code' => '1000013',
                    'msg' => '取票失败，请稍后再试'
                ]);
            }
        }else{
            return json([
                'code' => '10000013',
                'msg' => '请求方法错误,请稍后重试',
            ]);
        }
    }

    /**
     * 联网锁定座位
     * @Author   xiaoxiao972521
     * @DateTime 2019-12-06T15:11:07+0800
     * @return   [type]                   [description]
     */
    public function lockSeat(){
        if(request()->method() == "POST"){
            $data = request()->POST();
            //将请求放入队列,整个数据都放到队列
            Cache::store('redis')->lpush('user_list', serialize($data));
            //判断队列数据是否为空
            while(Cache::store('redis')->lLen('user_list')){
                //取出队列值
                $data = unserialize(Cache::store('redis')->lpop('user_list'));
                //联合查询信息
                $result = Db::table('U_xlzdb')
                ->join('U_xlb', 'U_xlzdb.xlbh = U_xlb.xlbh')
                ->join('U_jhb', 'U_xlzdb.xlbh = U_jhb.xlbh')
                ->join('U_clb', 'U_jhb.ysbbkh = U_clb.bbkh')
                ->where([
                    ['mdzm', '=', $data['arrivalDepot']],
                    ['U_jhb.bcbh', '=', $data['busCode']],
                    ['U_xlb.xlzt', '=', '正常'],
                    ['U_jhb.ysbj', '=', '1'],
                    ['U_jhb.ysfcsj', 'like', $data['departTime'] . '%']
                    //['U_jhb.bczt', '=', '已报']
                ])
                ->field([
                    //检票口字段新增，报错标记
                    'U_xlb.jpk',
                    'U_jhb.ysfcsj',
                    'U_jhb.ysbbkh',
                    'U_jhb.bcbh', 
                    'U_xlzdb.lc', 
                    'U_xlzdb.mdzm', 
                    'U_xlzdb.ptpj', 
                    'U_xlzdb.zdpj', 
                    'U_xlzdb.hhpj', 
                    'U_xlzdb.tbpj', 
                    'U_xlb.ssgs',
                    'U_clb.zwgs',
                    'U_xlzdb.xlbh', 
                    'U_xlzdb.mdzh'])
                ->select();
                //判断车辆是否存在
                if(!count($result)){
                    return json([
                        'code' => '1000007',
                        'msg' => '查询失败，没有找到该车辆',
                    ]);
                }
                //车辆详情，此时认为只有一辆车
                foreach($result as $key){
                    //判断用户是否已经下过订单
                    //订单号：md5(身份证号_发车时间)
                    if(Cache::store('redis')->exists(md5($data['certCode'] . '_' . $key['ysfcsj']))){
                        //返回数据
                        return json([
                            'code' => '01',
                            'msg' => '成功',
                            'data' => Cache::store('redis')->get(md5($data['certCode'] . '_' . $key['ysfcsj']))
                        ]);
                    }
                    //没有订单则判断车辆缓存是否存在
                    if(Cache::store('redis')->exists($key['ysbbkh'] . '_' . $key['ysfcsj'])){
                        //判断是否还有剩余座位
                        //===========这句话可能有问题，我提前标记以下=========
                        if(count(Cache::store('redis')->get($key['ysbbkh'] . '_' . $key['ysfcsj']))){
                            //构建用户信息数据
                            $user_data = [
                                'orderNum' => md5($data['certCode'] . '_' . $key['ysfcsj']),
                                'boardDepot' => $data['startDepot'],
                                'orderCustomName' => $data['orderCustomName'],
                                'orderCustomPhone' => $data['orderCustomPhone'],
                                'certCode' => $data['certCode'],
                                'lockType' => $data['lockType'],
                                'orderLockTime' => $data['orderLockTime'],
                                'customInfos' => []
                            ];
                            $i = 0;
                            foreach ($data['customInfos'] as $value) {
                                //继续构建用户信息数据
                                $user_data['customInfos'][$i] = [
                                    'ticketType' => $value['ticketType'],
                                    'ticketPrice' => $value['ticketPrice'],
                                    'seatCode' => $value['seatCode'],
                                    'customCertType' => $value['customCertType'],
                                    'customCertCode' => $value['customCertCode'],
                                    'customName' => $value['customName'],
                                    'customPhone' => $value['customPhone'],
                                ];
                                //应判断座位是否为0
                                if($value['seatCode'] == 0){
                                    //系统选座
                                    $arr = Cache::store('redis')->get($key['ysbbkh'] . '_' . $key['ysfcsj']);
                                    $seatCode[$i] = array_pop($arr);
                                    Cache::store('redis')->set($key['ysbbkh'] . '_' . $key['ysfcsj'], $arr);
                                }else{
                                    //个人选座
                                    $seatCode[$i] = $value['seatCode'];
                                    $arr = array_diff(Cache::store('redis')->get($key['ysbbkh'] . '_' . $key['ysfcsj']), $seatCode);
                                    Cache::store('redis')->set($key['ysbbkh'] . '_' . $key['ysfcsj'], $arr);
                                }
                                $i = $i + 1; 
                            }
                            //订单写入
                            //启动事务
                            Db::startTrans();
                            try{
                                //插入数据
                                Db::table('U_ddb')->insert([
                                    'ddzt' => '0',
                                    'bbkh' => $key['ysbbkh'],
                                    'fcsj' => $key['ysfcsj'],
                                    'bcbh' => $key['bcbh'],
                                    'qszh' => $data['startDepot'],
                                    'mdzh' => $key['mdzh'],
                                    'czbh' => '未知',
                                    'jpk' => $key['jpk'],
                                    'qph' => $data['certCode'],
                                    'qpmm' => md5($data['certCode']),
                                    'cp_ids' => '',
                                    'ddh' => md5($data['certCode'] . '_' . $key['ysfcsj']),
                                    'cplx' => $data['lockType'],
                                ]);
                                $sp = Db::table('U_yhb')
                                ->whereOr([
                                    ['yhbh', '=', 'sp_dz'],
                                    ['yhbh', '=', 'sp_sgs']
                                ])
                                ->field([
                                    'yhbh',
                                    'yhxm',
                                    'qsph',
                                    'zzph',
                                    'yhgroup'
                                ])
                                ->select();
                                //判断买票公司为东站还是邯大三公司
                                foreach($sp as $item){
                                    //线路表公司名不符，所以直接判断
                                    if($item['yhgroup'] == '三公司'){
                                        $ph = $item;
                                    }
                                    /*if($item['yhgroup'] == $key['ssgs']){
                                        $ph[] = $item;
                                    }*/
                                }
                                //判断已分配的票是否够用
                                if($ph['zzph'] < $ph['qsph']) {
                                    return json([
                                        'code' => '1000008',
                                        'msg' => '余票不足，购票失败',
                                    ]);
                                }
                                $ph['syps'] = $ph['zzph'] - $ph['qsph'];
                                //构建插入数据
                                $i = 0;
                                foreach($data['customInfos'] as $userInfo){
                                    $insert_arr[$i] = [
                                        'cpbh' => $ph['qsph'],
                                        'sfcz' => $data['startDepot'],
                                        'mdcz' => $data['arrivalDepot'],
                                        'spy' => $ph['yhxm'],
                                        'pj' => $userInfo['ticketPrice']-$key['tbpj'],
                                        'rqsj' => $key['ysfcsj'],
                                        'zwh' => $seatCode[$i],
                                        'cplx' => $userInfo['ticketType'],
                                        'cpzt' => '正常',
                                        'jpk' => $key['jpk'],
                                        'sfjp' => '未检',
                                        'bbkh' => $key['ysbbkh'],
                                        'spjs' => '未结',
                                        'tgjs' => '未结',
                                        'cljs' => '未结',
                                        'tbpj' => $key['tbpj'],
                                        'spsj' => date('Y-m-d H:i:s', time()),
                                        'xlbh' => $key['xlbh'],
                                        'mdzh' => $key['mdzh'],
                                        'ssgs' => $key['ssgs'],
                                        'bcbh' => $key['bcbh'],
                                        'yspbj' => '1',
                                        'ssdd' => md5($data['certCode'] . '_' . $key['ysfcsj']),
                                        'lkxm' => $userInfo['customName'],
                                        'sfzh' => $userInfo['customCertCode'],
                                        'elTicket' => md5($userInfo['customCertCode'] . '_' . $key['ysfcsj']),
                                    ];
                                    $ph['qsph'] = $ph['qsph'] + 1;
                                    $i = $i + 1;
                                    if($ph['syps'] - 1 < 0){
                                        return json([
                                            'code' => '1000008',
                                            'msg' => '余票不足，购票失败',
                                        ]);
                                    }
                                }
                                //插入数据
                                Db::table('U_cpb')->insertAll($insert_arr);
                                //更新用户表（车票编号）
                                Db::table('U_yhb')
                                ->where('yhbh', '=', $ph['yhbh'])
                                ->update([
                                    'qsph' => $ph['qsph']
                                ]);
                                //获取符合条件的车票编号
                                $ids = Db::table('U_cpb')
                                ->where('ssdd', '=', md5($data['certCode'] . '_' . $key['ysfcsj']))
                                ->field('cpbh')
                                ->select();
                                //将编号变成字符串
                                if(count($ids)){
                                    foreach($ids as $ids) {
                                        $ids_str = $ids['cpbh'] . ',';
                                    }
                                }else{
                                    $ids_str = '';
                                }
                                //存储对应订单下车票信息
                                Db::table('U_ddb')
                                ->where([
                                    'ddh' => md5($data['certCode'] . '_' . $key['ysfcsj'])
                                ])
                                ->update([
                                    'cp_ids' => $ids_str,
                                ]);
                                //更新车辆表座位信息
                                Db::table('U_clb')
                                ->where('bbkh', '=', $key['ysbbkh'])
                                ->update([
                                    'syzw' => count(Cache::store('redis')->get($key['ysbbkh'] . '_' . $key['ysfcsj']))
                                ]);
                                Cache::store('redis')->set(md5($data['certCode'] . '_' . $key['ysfcsj']), $user_data);
                                //提交事务
                                Db::commit();
                            }catch(\Exception $e){
                                //回滚事务
                                Db::rollback();
                            }
                            return json([
                            'code' => '01',
                            'msg' => '成功',
                            'data' => Cache::store('redis')->get(md5($data['certCode'] . '_' . $key['ysfcsj']))
                        ]);
                        }else{
                            return json([
                                'code' => '1000002',
                                'msg'  => '该车座票已售光'
                            ]);
                        }
                    }else{
                        return json([
                            'code' => '1000003',
                            'msg'  => '系统繁忙，稍后再试'
                        ]);
                    }
                }
            }
        }else{
            //404
            throw new \think\exception\HttpException(404, '页面不存在~');
        }
    }

    /**
     * 联网解锁座位
     * @Author   xiaoxiao972521
     * @DateTime 2019-12-07T15:43:28+0800
     * @return   [type]                   [description]
     */
    public function unLockSeat(){
        if(request()->method() == "POST"){
            $data = request()->POST();
            //接收订单号
            $ddh = $data['orderNum'];
            //判断订单是否存在
            if(Cache::store('redis')->exists($ddh)){
                //删除该订单缓存
                Cache::store('redis')->del($ddh);
            }
            try {
                //事务开始
                Db::startTrans();
                //删除对应订单车票信息
                Db::table('U_cpb')
                ->where('ssdd', '=', $ddh)
                ->delete();
                //删除订单
                Db::table('U_ddb')
                ->where('ddh', '=', $ddh)
                ->delete();
                //事务提交
                Db::commit();
                return json([
                    'code' => '01',
                    'message' => '成功',
                ]);
            } catch (Exception $e) {
                Db::rollBack();
                return json([
                    'code' => '1000009',
                    'msg' => '座位解锁失败，请稍后再试'
                ]);
            }
        }
    }

    /**
     * 电子票售票
     * @Author   xiaoxiao972521
     * @DateTime 2019-12-11T20:43:54+0800
     * @return   [type]                   [description]
     */
    public function elSellTicket(){
        if(request()->method() == "POST"){
            $data = request()->POST();
            //接收订单号
            $ddh = $data['orderNum'];
            //查询符合条件的订单
            $count = Db::table('U_ddb')
                    ->field('ddzt')
                    ->where('ddh', '=', $ddh)
                    ->select();
            //判断缓存是否存在，并且有符合条件的订单
            if(Cache::store('redis')->exists($ddh) && count($count)){
                //事务处理
                try {
                    Db::startTrans();
                    //======事务开始======
                    //更新订单状态
                    $result = Db::table('U_ddb')
                    ->where([
                        ['ddh', '=', $ddh],
                        ['ddzt', '=', 0],
                        ['cplx', '=', 1]
                    ])
                    ->update([
                        'ddzt' => 1,
                    ]);
                    //更新车票信息
                    if($result){
                        Db::table('U_cpb')
                        ->where('ssdd', '=', $ddh)
                        ->update([
                            'cljs' => '已结',
                        ]);
                    }
                    //======事务结束======
                    Db::commit();
                    //查询订单信息
                    $data = Db::table('U_ddb')
                            ->join('U_cpb', 'U_cpb.ssdd = U_ddb.ddh')
                            ->where('ddh', '=', $ddh)
                            ->field([
                                'U_ddb.qph',
                                'U_ddb.qpmm',
                                'U_cpb.jpk',
                                'U_cpb.spsj'
                            ])
                            ->select();
                    //返回构建数据
                    return json([
                        'code' => '01',
                        'msg' => '成功',
                        'data' => $data
                    ]);
                } catch (Exception $e) {
                    Db::rollBack();
                    return json([
                        'code' => '1000010',
                        'msg' => '数据库异常'
                    ]);
                }
            }elseif(!count($count)){
                return json([
                    'code' => '1000012',
                    'msg' => '订单不存在'
                ]);
            }elseif(!Cache::store('redis')->exists($ddh)){
                Db::table('U_ddb')
                ->where([
                    ['ddh', '=', $ddh],
                    ['cplx', '=', 1]
                ])
                ->update([
                    'ddzt' => 2,
                ]);
                return json([
                    'code' => '1000011',
                    'msg' => '订单失效'
                ]);
            }
        }
    }

    /**
     * 实体票售票
     * @Author   xiaoxiao972521
     * @DateTime 2019-11-11T09:10:02+0800
     * @return   [type]                   [description]
     */
    public function entitySellTicket(){
        if(request()->method() == "POST"){
            $data = request()->POST();
            //接收订单号
            $ddh = $data['orderNum'];
            $count = Db::table('U_ddb')
                    ->field('ddzt')
                    ->where('ddh', '=', $ddh)
                    ->select();
            if(Cache::store('redis')->exists($ddh) && count($count)){
                //事务处理
                try {
                    Db::startTrans();
                    //======事务开始======
                    $result = Db::table('U_ddb')
                    ->where([
                        ['ddh', '=', $ddh],
                        ['ddzt', '=', 0],
                        ['cplx', '=', 1]
                    ])
                    ->update([
                        'ddzt' => 1,
                    ]);
                    if($result){
                        Db::table('U_cpb')
                        ->where('ssdd', '=', $ddh)
                        ->update([
                            'cljs' => '已结',
                        ]);
                    }
                    //======事务结束======
                    Db::commit();
                    $data = Db::table('U_ddb')
                            ->join('U_cpb', 'U_cpb.ssdd = U_ddb.ddh')
                            ->where('ddh', '=', $ddh)
                            ->field([
                                'U_ddb.qph',
                                'U_ddb.qpmm',
                                'U_cpb.jpk',
                                'U_cpb.spsj'
                            ])
                            ->select();
                    return json([
                        'code' => '01',
                        'msg' => '成功',
                        'data' => $data
                    ]);
                } catch (Exception $e) {
                    Db::rollBack();
                    return json([
                        'code' => '1000010',
                        'msg' => '数据库异常'
                    ]);
                }
            }elseif(!count($count)){
                return json([
                    'code' => '1000012',
                    'msg' => '订单不存在'
                ]);
            }elseif(!Cache::store('redis')->exists($ddh)){
                Db::table('U_ddb')
                ->where([
                    ['ddh', '=', $ddh],
                    ['cplx', '=', 1]
                ])
                ->update([
                    'ddzt' => 2,
                ]);
                return json([
                    'code' => '1000011',
                    'msg' => '订单失效'
                ]);
            }
        }
    }

    /**
     * 实体票退票率查询
     * @Author   xiaoxiao972521
     * @DateTime 2019-11-18T16:13:27+0800
     * @return   [type]                   [description]
     */
    public function queryEntityTicketRefundRate(){
        if(request()->method() == "POST"){
            //接收全部参数
            $data = request()->POST();
            //接收实体票号
            $invoiceCode = $data['invoiceCode'];
            $invoiceNum = $data['invoiceNum'];
            //获取车票信息
            $result = Db::table('U_cpb')
            ->where('cpbh', '=', $invoiceCode)
            ->field([
                'rqsj',
                'pj',
                'tbpj',
            ])
            ->select();
            //获取当前时间
            $dqsj = date('Y-m-d H:i:s',time());
            //计算时间差(值为小时)
            $result_time = ceil((strtotime($dqsj)-strtotime($result[0]['rqsj']))/3600);
            //判断时间段
            if($result_time > 1){

                $refundRate = 0.10;

            }elseif($result_time < 1 && $result_time > 0){

                $refundRate = 0.20;

            }elseif($result_time < 0 && $result_time > -1){

                $refundRate = 0.50;

            }else{
                $refundRate = 1.00;
            }
            return json([
                'code' => '01',
                'msg' => '成功',
                'data' =>[
                    'totalAmount' => $result[0]['pj'] + $result[0]['tbpj'],
                    'refundRate' => $refundRate,
                    'refundFee' => ($result[0]['pj'] + $result[0]['tbpj']) * $refundRate,
                    'refundDesc' => '退票四舍五入，投诉电话0591-8888888',
                ]
            ]);
        }else{

            return json([
                'code' => '1000006',
                'msg' => '请求失败，请稍后重试~'
            ]);

        }
    }

    /**
     * 实体票退票
     * @Author   xiaoxiao972521
     * @DateTime 2020-01-06T15:47:12+0800
     * @return   [type]                   [description]
     */
    public function entityTicketRefund(){
        if(request()->method() == "POST"){
            $data = request()->POST();
            //车票信息
            $result = Db::table('U_cpb')
            ->where([
                ['cpbh', '=', $data['invoiceCode']],
                ['yspbj', '=', '1']
            ])
            ->whereOr([
                ['cpbh', '=', $data['invoiceNum']],
                ['yspbj', '=', '1']
            ])
            ->field([
                'rqsj',
                'bbkh',
                'zwh'
            ])
            ->select();
            //判断票是否存在
            if(!count($result)){
                return json([
                    'code' => '10000015',
                    'msg' => '查询失败，没有符合特征的车票'
                ]);
            }
            //退还座位
            if(Cache::store('redis')->exists($result[0]['bbkh'] . '_' . $result[0]['rqsj'])){
                //取出现有座位
                try {
                    //Cache::store('redis')->multi();
                    $seat = Cache::store('redis')->get($result[0]['bbkh'] . '_' . $result[0]['rqsj']);
                    $seat[] = $result[0]['zwh'];
                    Cache::store('redis')->set($result[0]['bbkh'] . '_' . $result[0]['rqsj'], $seat);
                    //Cache::store('redis')->exec();
                } catch (Exception $e) {
                    return json([
                        'code' => '1000005',
                        'msg' => '缓存写入失败，请检查Redis',
                    ]);
                }
            }else{
                return json([
                    'code' => '1000004',
                    'msg' => '发车时间已过，座位退还失败'
                ]);
            }
            $time = date('Y-m-d H:i:s', time());
            try {
                Db::startTrans();
                //======事务开始======
                //修改车票表
                Db::table('U_cpb')
                ->where([
                    ['cpbh', '=', $data['invoiceCode']],
                    ['yspbj', '=', '1']
                ])
                ->whereOr([
                    ['cpbh', '=', $data['invoiceNum']],
                    ['yspbj', '=', '1']
                ])
                ->update([
                    'cpzt' => '退票',
                    //'tgry' => $data['userName'],
                    'tgjs' => '已结',
                    //'tpsj' => $time,
                ]);
                //======事务结束======
                Db::commit();
                return json([
                    'code' => '01',
                    'msg' => '退票成功',
                    'data' => $time
                ]);
            } catch (Exception $e) {
                Db::rollBack();
                return json([
                    'code' => '1000010',
                    'msg' => '数据库异常'
                ]);
            }
        }
    }

    /**
     * 电子票退票率查询
     * @Author   xiaoxiao972521
     * @DateTime 2019-11-14T09:26:58+0800
     * @return   [type]                   [description]
     */
    public function queryElTicketRefundRate(){
        if(request()->method() == "POST"){
            //接收全部参数
            $data = request()->POST();
            //接收电子票号
            $el = $data['elTicket'];
            //获取车票信息
            $result = Db::table('U_cpb')
            ->where('elTicket', '=', $el)
            ->field([
                'rqsj',
                'pj',
                'tbpj',
            ])
            ->select();
            //获取当前时间
            $dqsj = date('Y-m-d H:i:s',time());
            //计算时间差(值为小时)
            $result_time = ceil((strtotime($dqsj)-strtotime($result[0]['rqsj']))/3600);
            //判断时间段
            if($result_time > 1){

                $refundRate = 0.10;

            }elseif($result_time < 1 && $result_time > 0){

                $refundRate = 0.20;

            }elseif($result_time < 0 && $result_time > -1){

                $refundRate = 0.50;

            }else{
                $refundRate = 1.00;
            }
            return json([
                'code' => '01',
                'msg' => '成功',
                'data' =>[
                    'totalAmount' => $result[0]['pj'] + $result[0]['tbpj'],
                    'refundRate' => $refundRate,
                    'refundFee' => ($result[0]['pj'] + $result[0]['tbpj']) * $refundRate,
                    'refundDesc' => '退票四舍五入，投诉电话0591-8888888',
                ]
            ]);
        }else{

            return json([
                'code' => '1000006',
                'msg' => '请求失败，请稍后重试~'
            ]);

        }
    }

    /**
     * 电子票退票
     * @Author   xiaoxiao972521
     * @DateTime 2019-11-14T15:24:47+0800
     * @return   [type]                   [description]
     */
    public function elTicketRefund(){
        if(request()->method() == "POST"){
            $data = request()->POST();
            //车票信息
            $result = Db::table('U_ddb')
            ->join('U_cpb', 'U_cpb.ssdd = U_ddb.ddh')
            ->where([
                ['U_ddb.ddh', '=', $data['orderNum']],
                ['U_cpb.elticket', '=', $data['elTicket']],
                ['U_ddb.ddzt', '=', '1'],
                ['U_ddb.cplx', '=', '1']
            ])
            ->field([
                'U_ddb.fcsj',
                'U_ddb.bbkh',
                'U_cpb.zwh'
            ])
            ->select();
            //判断票是否存在
            if(!count($result)){
                return json([
                    'code' => '10000015',
                    'msg' => '查询失败，没有符合特征的车票'
                ]);
            }
            //退还座位
            if(Cache::store('redis')->exists($result[0]['bbkh'] . '_' . $result[0]['fcsj'])){
                //取出现有座位
                try {
                    //Cache::store('redis')->multi();
                    $seat = Cache::store('redis')->get($result[0]['bbkh'] . '_' . $result[0]['fcsj']);
                    $seat[] = $result[0]['zwh'];
                    Cache::store('redis')->set($result[0]['bbkh'] . '_' . $result[0]['fcsj'], $seat);
                    //Cache::store('redis')->exec();
                } catch (Exception $e) {
                    return json([
                        'code' => '1000005',
                        'msg' => '缓存写入失败，请检查Redis',
                    ]);
                }
            }else{
                return json([
                    'code' => '1000004',
                    'msg' => '发车时间已过，座位退还失败'
                ]);
            }
            $time = date('Y-m-d H:i:s', time());
            try {
                Db::startTrans();
                //======事务开始======
                //修改车票表
                Db::table('U_cpb')
                ->where('elTicket', $data['elTicket'])
                ->update([
                    'cpzt' => '退票',
                    //'tgry' => $data['userName'],
                    'tgjs' => '已结',
                    //'tpsj' => $time,
                ]);
                //======事务结束======
                Db::commit();
                return json([
                    'code' => '01',
                    'msg' => '退票成功',
                    'data' => $time
                ]);
            } catch (Exception $e) {
                Db::rollBack();
                return json([
                    'code' => '1000010',
                    'msg' => '数据库异常'
                ]);
            }
        }
    }

    /**
     * 订单查询
     * @Author   xiaoxiao972521
     * @DateTime 2019-11-18T15:21:54+0800
     * @return   [type]                   [description]
     */
    public function queryOrder(){
        if (request()->method() == "POST") {
            //接收订单号以及电子客票唯一标识
            $data = request()->POST();
            //使用订单号以及电子客票唯一标识来查询该客户订单信息
            $ddb = Db::table('U_ddb')
                  ->where('ddh', '=', $data['orderNum'])
                  ->select();
            $cpb = Db::table('U_cpb')
                  ->where('ssdd', '=', $data['orderNum'])
                  ->select();
            if(count($ddb) && count($cpb)){
                return json([
                    'code' => '01',
                    'msg' => '成功',
                    'data' => [
                        'ddb' => $ddb,
                        'cpb' => $cpb,
                    ],
                ]);
            }else{
                return json([
                    'code' => '10000014',
                    'msg' => '请求无效',
                ]);
            }
        }else{
            return json([
                'code' => '10000013',
                'msg' => '请求方法错误,请稍后重试',
            ]);
        }
    }

    /**
     * 实体票查询
     * @Author   xiaoxiao972521
     * @DateTime 2019-12-18T17:47:26+0800
     * @return   [type]                   [description]
     */
    public function queryEntityTicket(){
        if (request()->method() == "POST") {
            $data = request()->POST();
            $cpb = Db::table('U_cpb')
                  ->where([
                    ['cpbh', '=', $data['invoiceNum']],
                    ['spjs', '=', '已结']
                ])
                  ->select();
            if(count($cpb)){
                return json([
                    'code' => '01',
                    'msg' => '成功',
                    'data' => $cpb,
                ]);
            }else{
                return json([
                    'code' => '10000014',
                    'msg' => '请求无效',
                ]);
            }
        }else{
            return json([
                'code' => '10000013',
                'msg' => '请求方法错误,请稍后重试',
            ]);
        }
    }

    //==========================+
    //         可能用不到        |
    //==========================+
    /**
     * 车站查询
     * @Author   xiaoxiao972521
     * @DateTime 2019-11-18T15:13:37+0800
     * @return   [type]                   [description]
     */
    /*public function queryStation(){

    }*/

    /**
     * 站点查询
     * @Author   xiaoxiao972521
     * @DateTime 2019-11-18T15:09:45+0800
     * @return   [type]                   [description]
     */
    /*public function queryDepot(){

    }*/
}
